﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;

namespace AthleteService
{
    public class DBHelper
    {
        /// <summary>
        /// 获取连接对象
        /// </summary>
        /// <returns></returns>
        public static SqlConnection GetConnection()
        {
            SqlConnection conn = null;
            string path = System.IO.Path.GetFullPath(@"../..");
            try
            {
                //可能发生错误的代码
                if (conn == null)
                {
                    conn = new SqlConnection();
                    conn.ConnectionString = "server=.;database=sportmeet;user=sa;pwd=Jackson.yi11.28";
                    conn.Open();
                    conn.Close();
                }
                return conn;
            }
            catch (Exception ex)
            {
                //发生异常以后要做的事情
                throw ex; // 把问题抛出，让程序员知道那里出了错误
            }
        }

        /// <summary>
        /// 执行增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int GetExcuet(string sql)
        {
            // 1. 获取连接对象
            SqlConnection conn = GetConnection();
            try
            {
                // 2.打开链接
                conn.Open();
                //3.创建SqlCommand对象,sql语句，连接对象
                SqlCommand cmd = new SqlCommand(sql, conn);
                // 4.执行SQL,并返回受影响的行数
                return cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }

        /// <summary>
        /// 返回执行查询的结果
        /// </summary>
        /// <returns></returns>
        public static DataTable GetDataSet(String sql)
        {
            try
            {
                // 1.获取链接对象
                SqlConnection conn = GetConnection();
                //2.创建适配器对象
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                //3.创建DataSet 对象
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


    }
}
